import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';
import { SelladPositionService } from '../sell-ad-position/sell-ad-position.service'
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-sell-ad-position-save',
  templateUrl: './sell-ad-position-save.component.html',
  styleUrls: ['./sell-ad-position-save.component.scss'],
  providers: [DatePipe]
})
export class SellAdPositionSaveComponent implements OnInit {

  // 路由传参
  routeForms: any ={
    mode: 0 // 0：新增,1：编辑,2：查看,3：复制
  };
  // formDatas
  formDatas: any = {
    // state: '', // 0启用 1禁用
    name: '', // 名称
    platform: '', // 渠道
    belongingBusiness: '', // 所属业务
    belongingPage: '', // 所属页面
    size: '', // 尺寸/比例
    remark: '', // 备注
    adverts: '', // 对应广告ID多个用逗号隔开
  }
  // 适用用户 b端=门店商户，c端=个人用户
  checkOptions: any = [
    { label: 'B端', value: '2' },
    { label: 'C端', value: '1' }
  ]
  // subLoading
  subLoading: boolean = false;

  // 渠道list
  channelLists: any = [];
  // 已选渠道
  channelSelected: any = [];
  // 业务list
  businessLists: any = [];

  // 已选table
  tableData: any = [];

  // modelTable
  isVisible: boolean = false;
  modelSeachForms: any = {
    title: ''
  }
  modelTableData: any = [];
  modelTableForms: any = {
    tableLoading: false,
    page: 1,
    pageSize: 10,
    total: 0
  };

  // modelTable****** 勾选
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = []; // 当前展示页面数据
  setOfCheckedId = new Set<number>(); // 已选ids
  setofCheckedArrs: object[] = []; // 已选项数组

  /**********************************************model表格勾选操作 START**********************************************/ 
  // 勾选设置
  updateCheckedSet(id: number, checked: boolean, item?: any): void {
    if (checked) {
      this.setOfCheckedId.add(id);

      if (this.setofCheckedArrs.length > 0) {
        let isHas = this.setofCheckedArrs.some((tag: any) => { return tag.id == id });
        if (!isHas) {
          this.setofCheckedArrs.push(item);
        }
      } else {
        this.setofCheckedArrs.push(item);
      }
    } else {
      this.setOfCheckedId.delete(id);

      let delIndex = this.setofCheckedArrs.findIndex((tag: any) => { return tag.id == id });
      this.setofCheckedArrs.splice(delIndex, 1);
    }
  }
  // 单选
  onItemChecked(id: number, checked: boolean, item?: any): void {
    this.updateCheckedSet(id, checked, item);
    this.refreshCheckedStatus();
  }
  // 全选
  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value, item));
    this.refreshCheckedStatus();
  }
  // 当前页面展示数据改变的回调函数
  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }
  // 全选按钮状态
  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }
  /**********************************************model表格勾选操作 END**********************************************/ 

  constructor(
    private datePipe: DatePipe,
    private message: NzMessageService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private service: SelladPositionService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeForms = res || {};
    })
  }

  ngOnInit() {
    // 渠道
    this.queryChannelData()
    // 业务
    this.queryBusinessData()

    if (this.routeForms.id) {
      this.queryDetailsData()
    }
  }

  // 查询详情
  queryDetailsData() {
    this.service.queryDetailData({ id: this.routeForms.id }).subscribe((res: any) => {
      const { data } = res

      if (data) {
        for (let key in this.formDatas) {
          this.formDatas[key] = String(data[key])
        }
        
        this.tableData = data.advertList || [];
        this.channelSelected = data.platform ? data.platform.split(',') : [];
      }
    })
  }

  // 已选tbale列表删除关联项
  deleteItems(index: number) {
    this.tableData.splice(index, 1);
  }

  // model广告查询
  getAdvertisementTableData() {
    const params = {
      ...this.modelSeachForms,
      page: this.modelTableForms.page,
      pageSize: this.modelTableForms.pageSize
    }

    this.modelTableForms.tableLoading = true;
    this.service.advertisementTableData(params).subscribe((res: any) => {
      this.modelTableForms.tableLoading = false;

      this.modelTableData = res.data.records || [];
      this.modelTableForms.total = res.data.total || 0;
    }, (error: any) => {
      this.modelTableForms.tableLoading = false;
      this.modelTableData = [];
      this.modelTableForms.total = 0;
    })
  }

  // model搜索
  seachData() {
    this.modelTableForms.page = 1;
    this.getAdvertisementTableData()
  }

  // 关联已选商品
  relationData() {
    if (this.setOfCheckedId.size <= 0) {
      this.message.warning('请先选择广告');
      return
    }

    this.tableData = this.setofCheckedArrs || [];
    this.isVisible = false;
  }

  // model弹出
  selectModel() {
    this.setOfCheckedId.clear();
    
    this.tableData.forEach((ele: any) => {
      this.setOfCheckedId.add(ele.id);
    });
    this.setofCheckedArrs = JSON.parse(JSON.stringify(this.tableData));

    this.modelSeachForms.page = 1;
    this.getAdvertisementTableData()
    this.isVisible = true;
  }
  // model确定
  handleOk(): void {
    this.isVisible = false;
  }
  // model取消
  handleCancel(): void {
    this.isVisible = false;

    this.setOfCheckedId.clear();
    this.setofCheckedArrs = [];
  }

  /**
   * 保存
   * routeForms.mode 0：新增,1：编辑,2：查看,3：复制
   * @returns 
   */
  subFormData() {
    if (!this.verifyData()) {
      return
    }
    
    // table表格数据处理
    if (this.tableData.length > 0) {
      this.formDatas.adverts = this.tableData.map((item: any) => { return item.id }).join(',');
    } else {
      this.formDatas.adverts = '';
    }

    let params = {
      ...this.formDatas
    }
    if (this.routeForms.mode == 1) {
      params.id = this.routeForms.id
    }
    
    this.subLoading = true;
    if (this.routeForms.mode == 0) {
      this.service.addAdvertisingSpaceData(params).subscribe((res: any) => {
        this.subLoading = false;

        if (res.code == 0) {
          this.message.success('操作成功');
          this.router.navigate(['/sell/adPosition']);
        } else {
          this.message.error(res.message || '操作失败');
        }
      }, (error: any) => {
        this.message.error(error || '操作失败');
      })
    } else {
      this.service.modifyData(params).subscribe((res: any) => {
        this.subLoading = false;

        if (res.code == 0) {
          this.message.success('操作成功');
          this.router.navigate(['/sell/adPosition']);
        } else {
          this.message.error(res.message || '操作失败');
        }
      }, (error: any) => {
        this.message.error(error || '操作失败');
      })
    }
  }

  // 渠道选择change
  channelChange(event: any) {
    this.formDatas.platform = event.length ? event.join(',') : '';
  }

  // 查询渠道
  async queryChannelData() {
    let data: any = await this.queryDictionariesData('channel');
    this.channelLists = data || [];
  }

  // 查询业务
  async queryBusinessData() {
    let data: any = await this.queryDictionariesData('business');
    this.businessLists = data || []
  }

  /**
   * 字典查询
   * @param parentKey 父类字典编码
   */
  async queryDictionariesData(parentKey: any) {
    const res: any = await this.service.dictListData(parentKey);
    return res.data.list
  }

  // 页面跳转
  jumpPage(item: any) {
    this.router.navigate(['/sell/adSave'], {
      queryParams: {
        id: item.id,
        mode: 1
      }
    })
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.modelTableForms.page = index;
    this.getAdvertisementTableData()
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.modelTableForms.page = 1;
    this.modelTableForms.pageSize = sizeNum;

    this.getAdvertisementTableData()
  }

  // 拖拽排序
  drop(event: CdkDragDrop<string[]>): void {
    moveItemInArray(this.tableData, event.previousIndex, event.currentIndex);
  }

  // 验证
  verifyData() {
    if (!this.formDatas.name) {
      this.message.warning('请输入名称');
      return false
    }
    return true
  }
}
